import express from "express";
import { structure_model, unit_model } from "../../db/system/base_set.js";

const router = express.Router();

router.get("/unit", async (req, res) => {
  const { name, address, page = 1 } = req.query;
  const query = {};
  if (name) {
    query.name = { $regex: name, $options: "i" };
  }
  if (address) {
    query.address = { $regex: address, $options: "i" };
  }
  const total = await unit_model.countDocuments(query);
  const unit = await unit_model
    .find(query)
    .skip((Number(page) - 1) * 10)
    .limit(12);

  res.send({ data: unit, page, total });
});

router.post("/unit/add", async (req, res) => {
  try {
    await unit_model.create(req.body);
    res.status(200).send({ msg: "添加成功" });
  } catch (err) {
    res.status(500).send({ msg: "添加失败" });
    console.log(err);
  }
});

router.get("/stucture", async (req, res) => {
  const total = await structure_model.countDocuments();
  const data = await structure_model.find();
  res.send({ data, total });
});

router.post("/stucture/add", async (req, res) => {
  try {
    const body = req.body
    if (body._id){
        // 删除_id
        delete body._id
    }
    await structure_model.create(body);
    res.status(200).send({ msg: "添加成功" });
  } catch (err) {
    res.status(500).send({ msg: "添加失败" });
    console.log(err);
  }
});

router.put("/stucture/update", async (req, res) => {
  console.log(req.body);
  try {
    await structure_model.updateOne({ _id: req.body._id }, req.body);
    res.status(200).send({ msg: "更新成功" });
  } catch (err) {
    res.status(500).send({ msg: "更新失败" });
    console.log(err);
  }
});

router.delete("/stucture/del", async (req, res) => {
  console.log(req.body);
  try {
    await structure_model.deleteOne({ _id: req.body._id });
    res.status(200).send({ msg: "更新成功" });
  } catch (err) {
    res.status(500).send({ msg: "更新失败" });
    console.log(err);
  }
});
export default router;
